package mo.leetcode_top;

public class L14 {

    public String longestCommonPrefix(String[] strs) {
        if (strs.length <= 0) {
            return "";
        }
        /**
         * 如果只有一个直接返回
         */
        if (strs.length == 1) {
            return strs[0];
        }
        StringBuilder builder = new StringBuilder();
        int min = Integer.MAX_VALUE;
        for (String str : strs) {
            min = Math.min(min, str.length());
        }
        for (int i = 0; i < min; i++) {
            for (int j = 1; j < strs.length; j++) {
                if (strs[j].charAt(i) != strs[0].charAt(i)) {
                    /**
                     * 遇到不符合的也直接返回
                     */
                    return builder.toString();
                }
                if (j == strs.length - 1) {
                    builder.append(strs[0].charAt(i));
                }
            }
        }
        return builder.toString();
    }

    public static void main(String[] args) {
        L14 test = new L14();
        System.out.println(test.longestCommonPrefix(new String[]{"dog","racecar","car"}));
    }
}
